<template>
  <div class="p-2">
    <a-card title="企业认证" :bordered="false" style="width: 100%;height:88vh">
      <a-spin :spinning="confirmLoading">
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-row>
            <a-col :span="24">

                <a-form-item label="公司Logo" v-bind="validateInfos.companyLogo">
                  <j-image-upload :fileMax=1 v-model:value="formData.companyLogo"
                                  :disabled="formData.authStatus==0 || formData.authStatus==2" ></j-image-upload>

                </a-form-item>
            </a-col>

            <a-col :span="24">
              <a-spin tip="OCR识别中..." :spinning="ocrReg">
                <a-form-item label="营业执照" v-bind="validateInfos.businessLicense">
                  <j-image-upload :fileMax=1 v-model:value="formData.businessLicense"
                                  :disabled="formData.authStatus==0 || formData.authStatus==2" @change="changeImage"></j-image-upload>
                  <span style="color: grey;font-size: 0.9em"> 图片上传后支持文字信息自动录入</span>
                </a-form-item>
              </a-spin>


            </a-col>
            <a-col :span="24" v-if="formData.id">
              <a-form-item label="认证状态" v-bind="validateInfos.authStatus">
                <!--                <j-dict-select-tag type='radio' v-model:value="formData.authStatus"
                                                   dictCode="company_auth_status" placeholder="请选择认证状态"
                                                   :disabled="disabled"/>-->
                <!--            认证中	0
                                待签约	1
                                已认证	2-->
                <div v-if="formData.authStatus==0">
                  <span style="color:red;font-size: 0.9em">认证中</span>
                </div>

                <a-space v-else-if="formData.authStatus==1">
                  <span style="color:orange;font-size: 0.9em">待签约</span>
                  <a style="font-size: 0.9em">去签约</a>
                  <a style="font-size: 0.9em" @click="submitForm">重新认证</a>
                </a-space>

                <div v-else-if="formData.authStatus==2">
                  <span style="color:green;font-size: 0.9em">已认证</span>
                </div>

              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="企业名称" v-bind="validateInfos.companyName">
                <a-input v-model:value="formData.companyName" placeholder="请输入企业名称"
                         :disabled="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="营业执照号码" v-bind="validateInfos.businessLicenseNo">
                <a-input v-model:value="formData.businessLicenseNo" placeholder="请输入营业执照号码"
                         :disabled="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="法人姓名" v-bind="validateInfos.legalName">
                <a-input v-model:value="formData.legalName" placeholder="请输入法人姓名"
                         :disabled="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24" v-if="!formData.id">
              <a-row justify="center">
                <a-button type="primary" @click="submitForm" :loading="confirmLoading">提交
                </a-button>
              </a-row>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </a-card>
  </div>
</template>

<script lang="ts" name="company-auth" setup>

import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
import {computed, defineProps, nextTick, reactive, ref} from "vue";
import {Form} from "ant-design-vue";
import {useMessage} from "@/hooks/web/useMessage";
import {getValueType} from "@/utils";
import {authCompany, info, ocrBusinessLicense, saveOrUpdate} from "@/views/company/WlhyCompany.api";


const props = defineProps({
  formDisabled: {type: Boolean, default: false},
  formData: {
    type: Object, default: () => {
    }
  },
  formBpm: {type: Boolean, default: true}
});
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  userId: '',
  businessLicense: '',
  authStatus: '',
  companyName: '',
  businessLicenseNo: '',
  legalName: '',
  status: '',
  busiRange: '',
  orgMode: '',
  regBalance: '',
  validDate: '',
  recBalance: '',
  validSdate: '',
  checkDate: '',
  bornDate: '',
  taxRegNu: '',
  addr: '',
  regOrg: '',
  companyType: '',
  companyLogo: '',
});
const {createMessage} = useMessage();
const labelCol = ref<any>({xs: {span: 24}, sm: {span: 5}});
const wrapperCol = ref<any>({xs: {span: 24}, sm: {span: 16}});
const confirmLoading = ref<boolean>(false);

const ocrReg = ref<boolean>(false);
//表单验证
const validatorRules = {
  companyLogo: [{required: true, message: '请上传公司Logo', trigger: 'change'}],
  businessLicense: [{required: true, message: '请上传营业执照', trigger: 'change'}],
};
const {
  resetFields,
  validate,
  validateInfos
} = useForm(formData, validatorRules, {immediate: false});

// 表单禁用
const disabled = computed(() => {
  /*if(props.formBpm === true){
    if(props.formData.disabled === false){
      return false;
    }else{
      return true;
    }
  }
  return props.formDisabled;*/
  return false;
});

/**
 * 获取企业信息
 */
const companyInfo = () => {
  confirmLoading.value = true;
  info({}).then(res => {
    edit(res);
  }).finally(() => {
    confirmLoading.value = false;
  })
}

/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 编辑
 */
function edit(record) {
  nextTick(() => {
    resetFields();
    const tmpData = {};
    Object.keys(formData).forEach((key) => {
      if (record.hasOwnProperty(key)) {
        tmpData[key] = record[key]
      }
    })
    //赋值
    Object.assign(formData, tmpData);
  });
}

const changeImage = async (e) => {
  if (!e) {
    createMessage.warning("请上传营业执照")
    return;
  }
  ocrReg.value = true;

  try {
    const ocrResult = await ocrBusinessLicense({image: e});
    console.log("ocr Result ", ocrResult);
    // 单位名称
    formData.companyName = ocrResult['单位名称'].words || '';
    // 地址
    formData.addr = ocrResult['地址'].words || '';
    // 实收资本
    formData.recBalance = ocrResult['实收资本'].words || '';
    // 成立日期
    formData.bornDate = ocrResult['成立日期'].words || '';
    // 有效期
    formData.validDate = ocrResult['有效期'].words || '';
    // 有效期起始日期
    formData.validSdate = ocrResult['有效期起始日期'].words || '';
    // 核准日期
    formData.checkDate = ocrResult['核准日期'].words || '';
    // 法人
    formData.legalName = ocrResult['法人'].words || '';
    // 注册资本
    formData.regBalance = ocrResult['注册资本'].words || '';
    // 登记机关
    formData.regOrg = ocrResult['登记机关'].words || '';
    // 社会信用代码
    formData.businessLicenseNo = ocrResult['社会信用代码'].words || '';
    // 税务登记号
    formData.taxRegNu = ocrResult['税务登记号'].words || '';
    // 类型
    formData.companyType = ocrResult['类型'].words || '';
    // 组成形式
    formData.orgMode = ocrResult['组成形式'].words || '';
    // 经营范围
    formData.busiRange = ocrResult['经营范围'].words || '';
    // 证件编号
    formData.idNo = ocrResult['证件编号'].words || '';
  } finally {
    ocrReg.value = false;
  }
}

/**
 * 提交数据
 */
async function submitForm() {
  // 触发表单验证
  await validate();
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  await authCompany(model)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        companyInfo();
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}

// -----------------
companyInfo();
</script>

<style lang="less" scoped>

</style>
